<template>
  <div>
    <el-table
      :data="tableData"
      style="width: 100%"
      row-key="roleCode"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'roleSon'}"
      ref="table"
    >
      <el-table-column prop="roleCode" label="角色Code"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleFcode" label="父Code"></el-table-column>
      <el-table-column prop="roleLevel" label="角色层级"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="modifyTime" label="修改时间"></el-table-column>
      <el-table-column prop="roleClient" label="所属端"></el-table-column>
      <el-table-column align="center" fixed="right" width="120">
        <template slot="header">
          <el-button type="text" size="small" @click="addDialog=true">新增</el-button>
        </template>
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="del(scope.row)" :loading="loadings.del">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Add :visible.sync="addDialog" @addSuccess="refreshRow"></Add>
  </div>
</template>
<script>
import { list, del } from "@/api/role";
import { Add } from "./components";
export default {
  data() {
    return {
      tableData: [],
      addDialog: false,
      loadings: {
        del: false
      }
    };
  },
  created() {
    this.list();
  },
  methods: {
    list() {
      list({ level: 0 }).then(res => {
        this.tableData = res.data;
      });
    },
    load(tree, treeNode, resolve) {
      list({ roleFcode: tree.roleCode }).then(res => {
        resolve(res.data);
      });
    },
    refreshRow(roleCode) {
      if (roleCode === "0") {
        this.list();
      } else {
        list({ roleFcode: roleCode }).then(res => {
          this.$set(
            this.$refs.table.store.states.lazyTreeNodeMap,
            roleCode,
            res.data
          );
        });
      }
    },
    del(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loadings.del = true;
        del(row.roleCode)
          .then(res => {
            this.loadings.del = false;
            this.refreshRow(row.roleFcode);
          })
          .catch(err => {
            this.loadings.del = false;
            this.refreshRow(row.roleFcode);
          });
      });
    }
  },
  components: {
    Add
  }
};
</script>